const CustomerData = require("../models/customerDataModel");

// Create a new customer data record
exports.createCustomerData = async (req, res) => {
  try {
    const {
      customerName,
      mobile,
      phone,
      email,
      gstNumber,
      panNumber,
      taxNumber,
      creditLimit,
      previousDue,
      country,
      city,
      area,
      state,
      postcode,
      locationLink,
      shippingcountry,
      shippingCity,
      shippingArea,
      shippingState,
      shippingPostcode,
      shippingLocationLink,
      attachmentPath,
      customerImage,

      // ADVANCED FIELDS
      priceLevelType,
      priceLevel,
      openingBalancePayments,
    } = req.body;

    const newCustomerData = new CustomerData({
      customerName,
      mobile,
      phone,
      email,
      gstNumber,
      panNumber,
      taxNumber,
      creditLimit,
      previousDue,
      attachmentPath: attachmentPath || "",
      customerImage: customerImage || "",
      address: {
        country,
        city,
        area,
        state,
        postcode,
        locationLink,
      },
      shippingAddress: {
        country: shippingcountry,
        city: shippingCity,
        area: shippingArea,
        state: shippingState,
        postcode: shippingPostcode,
        locationLink: shippingLocationLink,
      },
      // ADVANCED FIELDS
      priceLevelType: priceLevelType || "Increase",
      priceLevel: priceLevel || 0,
      openingBalancePayments: openingBalancePayments || [],
      // Accept advanceBalance if provided, defaulting to 0
      advanceBalance: req.body.advanceBalance || 0,
    });

    await newCustomerData.save();
    res.status(201).json({
      message: "Customer data created successfully",
      data: newCustomerData,
    });
  } catch (error) {
    console.error("Error creating customer data:", error);
    res.status(500).json({ message: "Server error", error: error.message });
  }
};

// Update a customer data record
exports.updateCustomerData = async (req, res) => {
  try {
    const { id } = req.params;

    // Extract fields from request body
    const {
      customerName,
      mobile,
      phone,
      email,
      gstNumber,
      panNumber,
      taxNumber,
      creditLimit,
      previousDue,
      attachmentPath,
      customerImage,

      country,
      city,
      area,
      state,
      postcode,
      locationLink,

      shippingcountry,
      shippingCity,
      shippingArea,
      shippingState,
      shippingPostcode,
      shippingLocationLink,

      // ADVANCED FIELDS
      priceLevelType,
      priceLevel,
      openingBalancePayments,
    } = req.body;

    // Build the updated object
    const updatedData = {
      customerName,
      mobile,
      phone,
      email,
      gstNumber,
      panNumber,
      taxNumber,
      creditLimit,
      previousDue,
      attachmentPath,
      customerImage: customerImage || "",
      address: {
        country,
        city,
        area,
        state,
        postcode,
        locationLink,
      },
      shippingAddress: {
        country: shippingcountry,
        city: shippingCity,
        area: shippingArea,
        state: shippingState,
        postcode: shippingPostcode,
        locationLink: shippingLocationLink,
      },
      
      priceLevelType: priceLevelType || "Increase",
      priceLevel: priceLevel || 0,
      
      openingBalancePayments: openingBalancePayments || [],
      
    };

    const customer = await CustomerData.findByIdAndUpdate(id, updatedData, {
      new: true,
    });
    if (!customer) {
      return res.status(404).json({ message: "Customer data not found" });
    }
    res.status(200).json({
      message: "Customer data updated successfully",
      data: customer,
    });
  } catch (error) {
    console.error("Error updating customer data:", error);
    res.status(500).json({ message: "Server error", error: error.message });
  }
};

// ata records
exports.getAllCustomerData = async (req, res) => {
  try {
    
    const customers = await CustomerData.find()
      .sort({ createdAt: -1 })
      .populate("openingBalancePayments.paymentType");
    res.status(200).json(customers);
  } catch (error) {
    console.error("Error fetching customer data:", error);
    res.status(500).json({ message: "Server error", error: error.message });
  }
};


exports.getCustomerDataById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const customer = await CustomerData.findById(id).populate(
      "openingBalancePayments.paymentType"
    );
    if (!customer) {
      return res.status(404).json({ message: "Customer data not found" });
    }
    res.status(200).json(customer);
  } catch (error) {
    console.error("Error fetching customer data:", error);
    res.status(500).json({ message: "Server error", error: error.message });
  }
};

// Delete a customer data record
exports.deleteCustomerData = async (req, res) => {
  try {
    const { id } = req.params;
    const customer = await CustomerData.findByIdAndDelete(id);
    if (!customer) {
      return res.status(404).json({ message: "Customer data not found" });
    }
    res.status(200).json({ message: "Customer data deleted successfully" });
  } catch (error) {
    console.error("Error deleting customer data:", error);
    res.status(500).json({ message: "Server error", error: error.message });
  }
};
